package com.gxar.quick.ar.server.base.common.utils;

import com.gxar.common.utils.SnowFlakeUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 分享码生成
 *
 * @author Linsy
 * @date 2023-11-02
 */
public class ShareCodeGenerator {

    private final static String SECRET_KEY = "8NPWsTnjI";

    /**
     * 加密code
     *
     * @param userId     用户id
     * @param businessId 业务id
     * @param salt       盐
     * @return code
     */
    public static String generateCode(long userId, long businessId, byte[] salt) {
        try {
            String input = userId + "|" + businessId + "|" + System.currentTimeMillis();

            // 使用PBE密钥工厂生成密钥
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            PBEKeySpec keySpec = new PBEKeySpec(SECRET_KEY.toCharArray());
            SecretKey secret = factory.generateSecret(keySpec);

            // 使用PBE加密算法加密数据
            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, 1000);
            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
            cipher.init(Cipher.ENCRYPT_MODE, secret, parameterSpec);
            byte[] encryptedBytes = cipher.doFinal(input.getBytes());

            // 将加密后的数据进行Base64编码
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密code
     *
     * @param encryptedUID code
     * @param salt         盐
     * @return 值
     */
    public static String decryptCode(String encryptedUID, byte[] salt) {
        try {
            // 使用PBE密钥工厂生成密钥
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            PBEKeySpec keySpec = new PBEKeySpec(SECRET_KEY.toCharArray());
            SecretKey secret = factory.generateSecret(keySpec);

            // 使用PBE加密算法解密数据
            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, 1000);
            Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
            cipher.init(Cipher.DECRYPT_MODE, secret, parameterSpec);

            // 解码Base64并解密数据
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedUID);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成盐
     *
     * @return 响应
     */
    public static String generateRandomSalt() {
        // 生成随机的字母和数字组合作为盐
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder salt = new StringBuilder();
        SecureRandom random = new SecureRandom();
        int saltLength = 8; // 盐的长度
        for (int i = 0; i < saltLength; i++) {
            salt.append(characters.charAt(random.nextInt(characters.length())));
        }
        return salt.toString();
    }

    public static void main(String[] args) {
        long userId = 12345;
        long resourceId = Long.parseLong(SnowFlakeUtils.getInstance().nextId());
        System.out.println(resourceId);
        String salt = generateRandomSalt();
        System.out.println(salt);

        // 生成短UID
        String shortUID = generateCode(userId, resourceId, salt.getBytes());
        System.out.println("Generated Short UID: " + shortUID);

        // 解密短UID
        String decryptedUID = decryptCode(shortUID, salt.getBytes());
        System.out.println("Decrypted UID: " + decryptedUID);
    }

}
